﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Rapid.Utility.Helper
{
    /// <summary>
    /// 字符串处理
    /// </summary>
    public static class StringHelper
    {
        /// <summary>
        /// 裁剪指定长度文本(兼容中文)
        /// </summary>
        /// <param name="value">原文本</param>
        /// <param name="length">指定长度</param>
        /// <returns>裁剪后文本</returns>
        public static string Cut(this string value, int length)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);

            StringBuilder sb = new StringBuilder();
            char[] stringChar = value.ToCharArray();

            int nLength = 0; bool isCut = false;

            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]); nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]); nLength += 1;
                }

                if (nLength > length) { isCut = true; break; }
            }

            if (isCut) { return sb.ToString() + "..."; } else { return sb.ToString(); }
        }

        /// <summary>
        /// 过滤所有HTML标签
        /// </summary>
        /// <param name="value">HTML</param>
        /// <returns>过滤后的字符串</returns>
        public static string FilterHTML(this string value)
        {
            //删除脚本  
            value = Regex.Replace(value, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);

            //删除HTML  
            value = Regex.Replace(value, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"-->", "", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"<!--.*", "", RegexOptions.IgnoreCase);

            value = Regex.Replace(value, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            value = Regex.Replace(value, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            value.Replace("<", "");
            value.Replace(">", "");
            value.Replace("\r\n", "");

            return HttpContext.Current.Server.HtmlEncode(value).Trim();
        }

        /// <summary>
        /// UCS2解码
        /// </summary>
        /// <param name="value">UCS2源串</param>
        /// <returns>解码后的UTF-16BE字符串</returns>
        public static string DecodeUCS2(this string value)
        {
            string decucs = value.Remove(value.IndexOf("\r"));
            string pstr = "^[0-9a-fA-F]+$";

            if (!Regex.IsMatch(decucs, pstr))
            {
                return "非法字符串无法解析！";
            }

            StringBuilder builer = new StringBuilder();

            for (int i = 0; i < decucs.Length; i += 4)
            {
                int unicode_nu = Int32.Parse(decucs.Substring(i, 4), System.Globalization.NumberStyles.HexNumber);
                builer.Append(string.Format("{0}", (char)unicode_nu));
            }

            return builer.ToString();
        }

        /// <summary>
        /// UCS2编码
        /// </summary>
        /// <param name="value">UTF-16BE编码的源串</param>
        /// <returns>编码后的UCS2串</returns>
        public static string EncodeUCS2(this string value)
        {
            StringBuilder builer = new StringBuilder();

            builer.Append("000800");

            byte[] tmpSmsText = Encoding.Unicode.GetBytes(value);

            builer.Append(tmpSmsText.Length.ToString("X2")); //正文内容长度

            for (int i = 0; i < tmpSmsText.Length; i += 2) //高低字节对调 
            {
                builer.Append(tmpSmsText[i + 1].ToString("X2"));//("X2")转为16进制
                builer.Append(tmpSmsText[i].ToString("X2"));
            }

            return builer.Remove(0, 8).ToString();
        }

        /// <summary>
        /// 从流中读取字符串
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string ReadByStream(Stream stream)
        {
            if (stream == null)
            {
                return string.Empty;
            }

            stream.Seek(0, SeekOrigin.Begin);

            using (StreamReader sr = new StreamReader(stream))
            {
                return sr.ReadToEnd();
            }
        }

        /// <summary>
        /// 获取GUID精简版
        /// </summary>
        /// <returns></returns>
        public static string NewGuid()
        {
            return Guid.NewGuid().ToString().Replace("-", string.Empty);
        }
    }
}